//
//  CityForumViewController.m
//  cityStar
//
//  Created by joyban on 15-2-6.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "CityForumViewController.h"
#import "CityForumCell.h"
#import "UIColor+FlatUI.h"
#import "SVPullToRefresh.h"
#import "cpostsModel.h"
#import "WritePostViewController.h"
#import "CityCommunityDetailViewController.h"
#import "SearchCommunityViewController.h"

NSString *const CityForumCellID = @"CityForumCellID";

@interface CityForumViewController ()<CSCityFourmDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *CityFourmTableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@end

@implementation CityForumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"社区论坛";
    [self addBackButton];
    [self setUpTableViews];
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithTitle:@"发贴" actionBlock:^{
        WritePostViewController *postVC = [[WritePostViewController alloc]init];
        [weakSelf.navigationController pushViewController:postVC animated:YES];
    }];
    
    [self.CityFourmTableView addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [self webRequest_getForum:NO];
    }];
    [self.CityFourmTableView addInfiniteScrollingWithActionHandler:^{
        [self webRequest_getForum:YES];
    }];
    [self.CityFourmTableView triggerPullToRefresh];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.page = 1;
    [self webRequest_getForum:NO];
}

-(void)webRequest_getForum:(BOOL)isMore
{
    NSString *postUrl  = [NSString stringWithFormat:@"%@/page/%d",KinterFace_Mycposts,isMore?self.page:0];
    [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
            }
            if(self.arrayRequest.count == 0)
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"暂无绑定社区，无法查看，请前往绑定." message:nil delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否",nil];
                [alertView show];

            }
            [self.CityFourmTableView reloadData];
        }
        if (isMore) {
            [self.CityFourmTableView.infiniteScrollingView stopAnimating];
        }else{
            [self.CityFourmTableView.pullToRefreshView stopAnimating];
        }
    }];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (buttonIndex == 0) {
        SearchCommunityViewController *searchVC = [[SearchCommunityViewController alloc]init];
        [self.navigationController pushViewController:searchVC animated:YES];
    }
}


-(void)setUpTableViews
{
    [self.CityFourmTableView registerNib:[CityForumCell nib] forCellReuseIdentifier:CityForumCellID];
}

- (void)addRightButtonWithTitle:(NSString *)title actionBlock:(void(^)(void))block
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setFrame:CGRectMake(0, 0, 50, 20)];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton setTitle:title forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightBar_Touched:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.rightBarActionBlock = block;
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tieziDidBtn:(UIButton *)btn
{
    
}

-(void)FourmDidBtn:(UIButton *)btn
{
    
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cpostsModel * model = [cpostsModel objectFromDictionary:self.arrayRequest[indexPath.section]];
    NSString * imagePathTwo = [NSString stringWithFormat:@"%@",model.image];
    if(![imagePathTwo isEqualToString:@"0"])
    {
        return [CityForumCell heightOfTableCell] + 120;
        
    }else{
        return [CityForumCell heightOfTableCell];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.arrayRequest.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 10)];
    [sectionView setBackgroundColor:[UIColor colorFromHexCode:@"F5F4F1"]];
    return sectionView;
}


#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CityForumCell *cityForumCell = [tableView dequeueReusableCellWithIdentifier:CityForumCellID];
    cityForumCell.selectionStyle = UITableViewCellSelectionStyleGray;
    cpostsModel * model = [cpostsModel objectFromDictionary:self.arrayRequest[indexPath.section]];
    cityForumCell.delegate = self;
    [cityForumCell setDatacpostsModel:model];
    return cityForumCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    cpostsModel * model = [cpostsModel objectFromDictionary:self.arrayRequest[indexPath.section]];
    CityCommunityDetailViewController *cityCommuityVC = [[CityCommunityDetailViewController alloc]init];
    cityCommuityVC.copmodel = model;
    [self.navigationController pushViewController:cityCommuityVC animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
